package com.google.zxing.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.camera.CameraManager;
import com.google.zxing.decoding.CaptureActivityHandler;
import com.google.zxing.decoding.InactivityTimer;
import com.google.zxing.decoding.QRCodeDecoder;
import com.google.zxing.view.ViewfinderView;
import com.yunshipei.base.BaseActivity;
import com.yunshipei.core.common.XCloudException;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.enterplorer.R;
import com.yunshipei.ui.activity.MainActivity;
import com.yunshipei.ui.activity.QRScanResultActivity;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.io.IOException;
import java.util.Vector;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.yunshipei.ui.activity.MainActivity.ACTION_QR_CODE_DATA_RESULT;
import static com.yunshipei.ui.activity.MainActivity.EXTRA_QR_CODE_CONTENT_IS_ADAPTER;

public class CaptureActivity extends BaseActivity implements Callback {

    private static final int REQUEST_CODE_SCAN_GALLERY = 100;
    private static final int QR_RESULT_REQUEST_CODE = 524;

    @Bind(R.id.viewfinder_content)
    protected ViewfinderView viewfinderView;

    private CaptureActivityHandler handler;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    public static final String INTENT_EXTRA_KEY_QR_SCAN = "qr_scan_result";

    public static final String INTENT_QR_SCAN_SERVICE = "intent_qr_scan_service";
    public static final String INTENT_QR_SCAN_RESULT = "intent_qr_scan_result";
    private String  is_return_result = "0";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_scanner);
        ButterKnife.bind(this);
        CameraManager.init(getApplication());
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);

        is_return_result = getIntent().getStringExtra(INTENT_QR_SCAN_SERVICE);
    }

    @OnClick({R.id.tv_qr_code_photo, R.id.iv_qr_code_back})
    protected void onClickFuc(View view) {
        switch (view.getId()) {
            case R.id.tv_qr_code_photo:
                Intent innerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
                startActivityForResult(wrapperIntent, REQUEST_CODE_SCAN_GALLERY);
                break;
            case R.id.iv_qr_code_back:
                finish();
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_SCAN_GALLERY && data != null) {
            final WaitDialog waitDialog = DialogHelper.getNoCancelableWaitDialog(this, "正在识别...");
            waitDialog.show();
            //获取选中图片的路径
            String path = "";
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                path = cursor.getString(columnIndex);
                cursor.close();
            }
            Flowable.just(path).flatMap(new Function<String, Publisher<String>>() {
                @Override
                public Publisher<String> apply(String fileName) throws Exception {
                    if (TextUtils.isEmpty(fileName)) {
                        return Flowable.error(new XCloudException("图片获取失败..."));
                    } else {
                        final String result = QRCodeDecoder.syncDecodeQRCode(fileName);
                        if (!TextUtils.isEmpty(result)) {
                            return Flowable.just(result);
                        } else {
                            return Flowable.error(new XCloudException("识别失败..."));
                        }
                    }
                }
            }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
                @Override
                public void accept(String result) throws Exception {
                    waitDialog.dismiss();
                    handlerContent(result);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    waitDialog.dismiss();
                    ToastUtils.showToast(XCloudSDKManager.getInstance().generateError(throwable));
                }
            });
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scanner_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * Handler scan result
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if(!TextUtils.isEmpty(is_return_result) && "1".equals(is_return_result)){
            Intent intent = new Intent();
            intent.putExtra(INTENT_QR_SCAN_RESULT,resultString);
            setResult(RESULT_OK,intent);
            finish();
        }else{
            handlerContent(resultString);
        }
    }

    private void handlerContent(String resultString) {
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(CaptureActivity.this, "扫描失败...", Toast.LENGTH_SHORT).show();
        } else {
            if (resultString.startsWith("http://") || resultString.startsWith("https://") || resultString.startsWith("file:///")) {
                startMainBrowser(resultString, false);
            } else {
                try {
                    //是云适配适配包开发者的内容
                    JSONObject jsonObject = new JSONObject(resultString);
                    if (jsonObject.has("url") && jsonObject.has("app") && jsonObject.has("runtime")) {
                        startMainBrowser(resultString, true);
                    } else {
                        openQRCodeContent(resultString);
                    }
                } catch (JSONException e) {
                    openQRCodeContent(resultString);
                }
            }
        }
    }

    //进入到浏览器加载
    private void startMainBrowser(String resultString, boolean adapter) {
        Intent intent = new Intent(this, MainActivity.class).setAction(ACTION_QR_CODE_DATA_RESULT).putExtra(INTENT_EXTRA_KEY_QR_SCAN, resultString).putExtra(EXTRA_QR_CODE_CONTENT_IS_ADAPTER, adapter);
        startActivity(intent);
    }

    //打开二维码内容显示页面
    private void openQRCodeContent(String result) {
        startActivityForResult(new QRScanResultActivity.ScanResultIntentBuilder(this).setData(result).getIntent(), QR_RESULT_REQUEST_CODE);
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

}